<template>
  <div class="menu-base-wrapper">
    <!-- 主要部分 -->
    <main class="user_main_part">
      <!-- 💭筛选框和按钮 -->
      <section class="search_part">
        <el-row style="width: 90%; margin: 0 auto">
          <el-col :span="6">
            <el-input style="width: 70%" size="mini" placeholder="菜单名称" v-model="name" clearable></el-input>
          </el-col>
          <el-col :span="6">
            <el-button type="primary" size="mini" icon="el-icon-search" @click="handleSearch">查询</el-button>
            <el-button size="mini" icon="el-icon-refresh" @click="handleReset">重置</el-button>
            <el-button type="primary" size="mini" icon="el-icon-plus" @click="handleAdd">新增</el-button>
          </el-col>
        </el-row>
      </section>
      <!-- 💭表格部分 -->
      <section
        default-expand-all
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        :header-cell-style="{ background: 'rgba(117, 60, 202, 0.04)' }"
        :stripe="true"
        class="tabel_part"
      >
        <el-table
          :header-cell-style="{ background: 'rgba(117, 60, 202, 0.04)' }"
          :stripe="true"
          row-key="id"
          size="mini"
          :data="tableData"
          @row-click="getOpenDetail"
        >
          <el-table-column label="序号" align="center" type="index" width="50"></el-table-column>
          <el-table-column
            label="名称"
            align="left"
            prop="name"
            min-width="200px"
            :show-overflow-tooltip="true"
          ></el-table-column>
          <el-table-column label="类型" align="left" prop="menuType" width="100">
            <template v-slot="{ row }">
              <el-tag v-if="row.menuType === 0" size="mini">目录</el-tag>
              <el-tag v-if="row.menuType === 1" size="mini" type="success">菜单</el-tag>
              <el-tag v-if="row.menuType === 2" size="mini" type="info">按钮</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="上级菜单" align="left" prop="parentName" width="140"></el-table-column>
          <el-table-column
            label="菜单URL/权限标识"
            align="center"
            prop="path"
            width="200"
            :show-overflow-tooltip="true">
            <template v-slot="{ row }">
              <span>{{ row.path || row.permission}}</span>
            </template>
          </el-table-column>
          <el-table-column label="排序" align="center" prop="sort" width="90"></el-table-column>
          <el-table-column label="操作" align="center" width="160px">
            <template v-slot="{ row }">
              <el-button type="text" icon="el-icon-edit" size="mini" @click="handleEdit(row)">编辑</el-button>
              <el-button type="text" icon="el-icon-delete" @click="handleDelete(row)" size="mini">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </section>
    </main>
    <!-- 💭弹窗 -->
    <el-dialog :visible.sync="diaVis" width="500px" @close="handleClose" :title="diaTitle">
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px">
        <div v-for="item in formColumns" :key="item.prop">
          <el-form-item :prop="item.prop" :label="item.label" v-if="item.show">
            <!-- 单选 -->
            <el-radio-group @change="handleRadioChange" v-if="item.ele === 'radio'" v-model="formData[item.prop]">
              <el-radio v-for="it in item.radios" :key="it.value" :label="it.value">{{ it.label }}</el-radio>
            </el-radio-group>
            <!-- 输入框 -->
            <el-input
              size="mini"
              v-if="item.ele === 'input'"
              v-model="formData[item.prop]"
              style="width: 90%"
              clearable
            ></el-input>
            <!-- 数组框 -->
            <el-input-number
              size="mini"
              v-if="item.ele === 'number'"
              v-model="formData[item.prop]"
              controls-position="right"
              style="width: 90%"
              clearable
            ></el-input-number>
            <!-- 输入框和tip的合并2 -->
            <el-row v-if="item.ele === 'inputTipTwo'" style="width: 90%" type="flex" justify="space-between">
              <el-col :span="21">
                <el-input size="mini" v-model="formData[item.prop]" clearable></el-input>
              </el-col>
              <el-col :span="2">
                <el-tooltip class="item" effect="light" placement="top">
                  <div slot="content">
                    <p>URL格式：</p>
                    <p>1.常规业务开发的功能URL，如用户管理，Views目录下页面路径为 /Sys/User, 此处填写 /sys/user。</p>
                    <p>2.嵌套外部网页，如通过菜单打开百度网页，此处填写 http://www.baidu.com，http:// 不可省略。</p>
                    <p>示例：用户管理：/sys/user 嵌套百度：http://www.baidu.com 嵌套网页：http://127.0.0.1:8000</p>
                  </div>
                  <i class="el-icon-warning"></i>
                </el-tooltip>
              </el-col>
            </el-row>
            <!-- 💭上级菜单 -->
            <el-popover v-if="item.ele === 'inputTree'" placement="right" trigger="click">
              <el-tree
                :data="treeData"
                :props="defaultProps"
                @node-click="handleNodeClick"
                :default-expand-all="false"
                :highlight-current="true"
              >
              </el-tree>
              <template slot="reference">
                <el-input size="mini" v-model="formData[item.prop]" style="width: 90%"></el-input>
              </template>
            </el-popover>
          </el-form-item>
        </div>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" size="mini" @click="btnConfirm">确认</el-button>
        <el-button size="mini" @click="btnCancel">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { mapActions } from 'vuex'
export default {
  name: 'menu-config',
  data() {
    return {
      name: '',
      diaVis: false,
      // 弹窗表单规则
      formColumns: [
        {
          ele: 'radio',
          prop: 'menuType',
          label: '菜单类型：',
          radios: [
            { label: '目录', value: 0 },
            { label: '菜单', value: 1 },
            { label: '按钮', value: 2 },
          ],
          show: true,
        },
        { ele: 'input', prop: 'name', label: '目录名称：', show: true },
        { ele: 'input', prop: 'menuName', label: '菜单名称：', show: false },
        { ele: 'input', prop: 'buttonName', label: '按钮名称：', show: false },
        { ele: 'inputTree', prop: 'parentName', label: '上级菜单：', show: true },
        { ele: 'input', prop: 'permission', label: '授权标识：', show: true },
        { ele: 'inputTipTwo', prop: 'path', label: '菜单路由：', show: false },
        { ele: 'number', prop: 'sort', label: '排序编号：', show: true },
      ],
      // 弹窗表单数据
      formData: {
        parentName: '',
        menuType: 0,
      },
      defaultFormData: {
        parentName: '',
        menuType: 0,
      },
      formRules: {
        menuType: [{ required: true, message: '请选择', trigger: 'chagne' }],
        name: [{ required: true, message: '请输入', trigger: 'blur' }],
        menuName: [{ required: true, message: '请输入', trigger: 'blur' }],
        buttonName: [{ required: true, message: '请输入', trigger: 'blur' }],
        parentName: [{ required: true, message: '请输入', trigger: 'change' }],
        path: [{ required: true, message: '请输入', trigger: 'blur' }],
      },
      diaTitle: '',
      tableData: [],
      diaIsAdd: true,
      treeData: '',
      defaultProps: {
        children: 'children',
        label: 'name',
      },
    }
  },
  created() {
    this.handleSearch()
  },
  watch: {},
  methods: {
    ...mapActions('menuConfig', ['getMenuDataAPI', 'addMenuDataAPI', 'editMenuDataAPI', 'deleteMenuDataAPI']),
    // 实现点击行，展开或者合并
    getOpenDetail(row, column, event) {
      console.log(event, 'event')
      if (column.label !== '操作') {
        event.currentTarget.querySelector('.el-table__expand-icon').click()
      }
    },

    // 查询
    handleSearch() {
      const params = {
        name: this.name,
      }
      this.getMenuDataAPI({ params }).then(res => {
        const { data, code, message } = res
        if (code === 200) {
          data.forEach(item => {
            item.parentName = '顶级菜单'
          })
          this.tableData = data
          const arr = [{ name: '顶级菜单', id: '0', children: [] }]
          arr[0].children.push(...data)
          this.treeData = arr
        } else {
          this.$message.error(message || '服务异常，请稍后重试!')
        }
      })
    },
    handleAdd() {
      this.diaTitle = '新增'
      this.diaIsAdd = true
      this.diaVis = true
    },
    handleReset() {
      this.name = ''
      this.handleSearch()
    },
    publicClose() {
      this.$refs.formRef.resetFields()
      this.formData = {
        ...this.defaultFormData,
      }
      this.diaVis = false
    },
    handleClose() {
      this.publicClose()
    },
    async btnConfirm() {
      await this.$refs.formRef.validate()
      const data = {
        ...this.formData,
      }
      // 后端返回数据需要处理
      if (this.formData.menuType === 0) {
        data.name = this.formData.name
      } else if (this.formData.menuType === 1) {
        data.name = this.formData.menuName
      } else if (this.formData.menuType === 2) {
        data.name = this.formData.buttonName
      }
      if (this.diaIsAdd) {
        // 新增
        this.addMenuDataAPI({ data }).then(res => {
          const { code, message } = res
          if (code === 200) {
            this.$message.success('创建成功')
            this.handleSearch()
            this.publicClose()
          } else {
            this.$message.error(message || '服务异常，请稍后重试!')
          }
        })
      } else {
        // 编辑
        this.editMenuDataAPI({ data }).then(res => {
          const { code, message } = res
          if (code === 200) {
            this.$message.success('修改成功')
            this.handleSearch()
            this.publicClose()
          } else {
            this.$message.error(message || '服务异常，请稍后重试!')
          }
        })
      }
    },
    btnCancel() {
      this.publicClose()
    },
    // 公共的表单变化逻辑
    publicFormChange(val) {
      if (val === 0) {
        this.formColumns[1].show = true
        this.formColumns[5].show = true
        this.formColumns[2].show = false
        this.formColumns[3].show = false
        this.formColumns[6].show = false
      } else if (val === 1) {
        this.formColumns[2].show = true
        this.formColumns[6].show = true
        this.formColumns[1].show = false
        this.formColumns[3].show = false
        this.formColumns[5].show = false
      } else if (val === 2) {
        this.formColumns[3].show = true
        this.formColumns[5].show = true
        this.formColumns[1].show = false
        this.formColumns[2].show = false
        this.formColumns[6].show = false
      }
    },
    handleRadioChange(val) {
      this.publicFormChange(val)
    },
    // 删除按钮
    handleDelete(row) {
      this.$confirm('确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          // 用户点击了确定按钮，执行相应的操作
          const params = {
            id: row.id,
          }
          this.deleteMenuDataAPI({ params }).then(res => {
            const { code, message } = res
            if (code === 200) {
              this.handleSearch()
              this.$message.success('删除成功')
            } else {
              this.$message.error(message || '服务异常，请稍后重试!')
            }
          })
        })
        .catch(() => {})
    },
    // 💭编辑按钮
    handleEdit(row) {
      this.diaTitle = '编辑'
      this.diaIsAdd = false
      this.publicFormChange(row.menuType)
      if (row.menuType === 1) {
        row.menuName = row.name
      } else if (row.menuType === 2) {
        row.buttonName = row.name
      }
      this.formData = { ...row }
      this.diaVis = true
    },
    // 树节点点击
    handleNodeClick(data, node, el) {
      this.formData.parentName = data.name
      this.formData.parentId = data.id
    },
  },
}
</script>
<style lang="scss" scoped>
.menu-base-wrapper {
  background-color: $white;
  height: 100%;
  .user_main_part {
    background-color: $white;
    padding: 12px;
    .search_part {
      margin-top: 12px;
    }
    .tabel_part {
      margin-top: 24px;
    }
  }
}
</style>
